package com.yuncheng.spcyApi.webOffice;

import com.yuncheng.spcyApi.alog.annotation.Log;
import com.yuncheng.spcyApi.config.SpcyMinioUtils;
import com.yuncheng.spcyApi.constant.common.SpcyConstant;
import com.yuncheng.spcyApi.entity.*;
import com.yuncheng.exception.BusinessException;
import com.yuncheng.spcyApi.flow.TxwjFlowService;
import com.yuncheng.spcyApi.mapper.SpcyZltxwjXgpxwjMapper;
import com.yuncheng.spcyApi.mapper.YcSysUserMapper;
import com.yuncheng.spcyApi.service.ISpcyFgbzkBasicService;
import com.yuncheng.spcyApi.service.ISpcyZltxwjBasicService;
import com.yuncheng.spcyApi.service.ISpcyZltxwjFlowService;
import com.yuncheng.spcyApi.service.ISpcyZltxwjHistoryService;
import com.yuncheng.spcyApi.spcyService.FgbzkBusService;
import com.yuncheng.spcyApi.utils.GetUuIdUtils;
import com.yuncheng.spcyApi.utils.LocalFileUploadUtils;
import com.yuncheng.vo.HttpResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import utils.DateConversionUtils;
import utils.ObjectToMapUtils;
import utils.Util;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Map;

@Api(tags = "质量体系文件-客户端在线文档编辑接口")
@RestController
@RequestMapping("/api/spzx-spcy/zltxwjClientOfficeApi")
public class ZltxwjClientOfficeApi {
    private static final Logger log = LoggerFactory.getLogger(ZltxwjClientOfficeApi.class);

    @Resource
    private ISpcyZltxwjFlowService spcyZltxwjFlowService;

    @Resource
    private ISpcyZltxwjBasicService spcyZltxwjBasicService;

    @Resource
    private ISpcyZltxwjHistoryService spcyZltxwjHistoryService;

    @Resource
    private LocalFileUploadUtils localFileUploadUtils;

    @Resource
    private YcSysUserMapper ycSysUserMapper;

    @Resource
    private SpcyMinioUtils spcyMinioUtils;

    @Resource
    private TxwjFlowService txwjFlowService;

    @Resource
    private ISpcyFgbzkBasicService spcyFgbzkBasicService;

    @Resource
    private FgbzkBusService fgbzkBusService;

    @Resource
    private SpcyZltxwjXgpxwjMapper spcyZltxwjXgpxwjMapper;

    /*@ApiOperation(value = "客户端-文件在线编辑-打开文件")
    @ApiImplicitParam(name = "id",value = "质量体系文件id",required = true)*/
    @GetMapping(value = "openWjjl")
    public void openWjjl(@RequestParam(value = "id",defaultValue = "")String id, HttpServletResponse response){
        if (StringUtils.isBlank(id)){
            log.error("【文件在线编辑】-文件id不能为空");
            return;
        }
        SpcyZltxwjFlow wjjl = spcyZltxwjFlowService.getById(id);
        if (wjjl == null){
            log.error("【文件在线编辑】-文件id:{}的数据不存在",id);
            return;
        }
        if (StringUtils.isNotBlank(wjjl.getFwjlj())){
            localFileUploadUtils.ejzLocalFileURlByZdy(wjjl.getFwjlj(),response);
        }else {
            log.error("【文件在线编辑】- 文件存放路径不存在");
            return;
        }
    }

    /*@ApiOperation(value = "客户端-在线编辑-保存文件")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "docfile",value = "保存的文件",required = true),
            @ApiImplicitParam(name = "id",value = "质量体系文件id",required = true)
    })
    @PostMapping(value = "onLineSaveWjjl")*/
    public HttpResult<?> onLineSaveWjjl(@RequestParam("docfile") MultipartFile file, @RequestParam(value = "id",defaultValue = "") String id){
        if (StringUtils.isBlank(id)){
            return HttpResult.error("质量体系文件id不能为空");
        }
        SpcyZltxwjFlow wjjl = spcyZltxwjFlowService.getById(id);
        if (wjjl == null){
            return HttpResult.error("文件数据不存在，请重试");
        }
        Map<String, Object> oldMap = ObjectToMapUtils.objectToMap(wjjl);

        String oldCflj = wjjl.getFwjlj(); // 旧文件存放路径

        String originalFilename = file.getOriginalFilename();

        if (originalFilename.lastIndexOf(".") == 0){
            return HttpResult.error("文件不存在这个格式，请联系管理员");
        }
        // 文件类型
        String wjlx = ".doc";
        // 文件名

        String sjmc = wjjl.getFwjmc() + GetUuIdUtils.NotReplaceUuId();
        String wjccmc = sjmc + wjlx;
        String nowDay = DateConversionUtils.DateToMonthTwo(new Date()); // 获取当前日期 yyyy-MM-dd
        String newDir = SpcyConstant.Flow_Zltxwj_File_Base_Url + "/" + nowDay;
        String cflj = "/" + newDir + "/" + wjccmc;

        localFileUploadUtils.uploadZdyFile(file, wjccmc,newDir); // 上传文件

        wjjl.setFwjlx(wjlx);
        wjjl.setFwjlj(cflj);
        boolean flag = spcyZltxwjFlowService.updateById(wjjl);
        if (flag) {
            localFileUploadUtils.deleteLocalFileUrlByZdy(oldCflj); // 删除旧的文件
        }

        return HttpResult.ok("保存文件成功");
    }

    @Log(title = "质量体系文件库-查看文件")
    @ApiOperation(value = "质量体系文件-查看文件")
    @GetMapping(value = "/getZltxwjFile")
    public void getZltxwjFile(@RequestParam(value = "id",defaultValue = "") String fileId,
                              @RequestParam(value = "symc",defaultValue = "") String symc,
                              @RequestParam(value = "fuserid",defaultValue = "") String fuserid,
                              HttpServletResponse response) {
        if (StringUtils.isEmpty(fileId)){
            log.error("质量体系文件id为空");
            throw new BusinessException("质量体系文件参数为空");
        }

        SpcyZltxwjBasic zltxwj = spcyZltxwjBasicService.getById(fileId);
        if (zltxwj == null){
            throw new BusinessException("质量体系文件id为-{}的文件记录不存在"+fileId);
        }

        if (StringUtils.isNotBlank(fuserid)){
            String realname = ycSysUserMapper.findRealnameById(fuserid);
            symc = StringUtils.isNotBlank(realname) ? realname+DateConversionUtils.DateToString(new Date()) : symc;
        }

        if (StringUtils.isBlank(zltxwj.getFpdfurl())){
            if (StringUtils.isNotBlank(zltxwj.getFwjlj())){
                SpcyZltxwjBasic zltxwj2 = null;
                if (StringUtils.isBlank(zltxwj.getFzt()) || zltxwj.getFzt().equals(SpcyConstant.Zltxwj_Zt_Yx)){
                    zltxwj2 = txwjFlowService.zltxwjToPdf(zltxwj, false, true, false);
                }else {
                    zltxwj2 = txwjFlowService.zltxwjToPdf(zltxwj, false, true, true);
                }

                if (zltxwj2 != null && StringUtils.isNotBlank(zltxwj2.getFpdfurl())) {
//                    localFileUploadUtils.ejzLocalFileURlByZltxwj(zltxwj2.getFpdfurl(), response);

                    this.ejzFileSy(zltxwj2.getFpdfurl(), symc, response);

                }else {
                    localFileUploadUtils.ejzLocalFileURlByZltxwj(zltxwj.getFwjlj(), response);
                }
            }else {
                throw new BusinessException("质量体系文件id为-{}的文件不存在"+fileId);
            }
        }else {
//            localFileUploadUtils.ejzLocalFileURlByZltxwj(zltxwj.getFpdfurl(), response);
            this.ejzFileSy(zltxwj.getFpdfurl(), symc, response);
        }
    }

    @Log(title = "法规标准库-查看文件")
    @ApiOperation(value = "法规标准库-查看文件")
    @GetMapping(value = "/getFgbzkFile")
    public void getFgbzkFile(@RequestParam(value = "id",defaultValue = "") String fileId,
                              @RequestParam(value = "symc",defaultValue = "") String symc,
                              @RequestParam(value = "fuserid",defaultValue = "") String fuserid,
                              HttpServletResponse response) {
        if (StringUtils.isEmpty(fileId)){
            log.error("质量体系文件id为空");
            throw new BusinessException("质量体系文件参数为空");
        }

        SpcyFgbzkBasic zltxwj = spcyFgbzkBasicService.getById(fileId);
        if (zltxwj == null){
            throw new BusinessException("质量体系文件id为-{}的文件记录不存在"+fileId);
        }

        if (StringUtils.isNotBlank(fuserid)){
            String realname = ycSysUserMapper.findRealnameById(fuserid);
            symc = StringUtils.isNotBlank(realname) ? realname+DateConversionUtils.DateToString(new Date()) : symc;
        }

        if (StringUtils.isBlank(zltxwj.getFpdfurl())){
            if (StringUtils.isNotBlank(zltxwj.getFwjlj())){
                SpcyFgbzkBasic zltxwj2 = null;
                if (StringUtils.isBlank(zltxwj.getFzt()) || zltxwj.getFzt().equals(SpcyConstant.Zltxwj_Zt_Yx)){
                    zltxwj2 = fgbzkBusService.zltxwjToPdf(zltxwj, false, true, false);
                }else {
                    zltxwj2 = fgbzkBusService.zltxwjToPdf(zltxwj, false, true, true);
                }

                if (zltxwj2 != null && StringUtils.isNotBlank(zltxwj2.getFpdfurl())) {
                    this.ejzFgbzkFileSy(zltxwj2.getFpdfurl(), symc, response);

                }else {
                    localFileUploadUtils.ejzLocalFileURlByFgbzk(zltxwj.getFwjlj(), response);
                }
            }else {
                throw new BusinessException("质量体系文件id为-{}的文件不存在"+fileId);
            }
        }else {
            this.ejzFgbzkFileSy(zltxwj.getFpdfurl(), symc, response);
        }
    }

    @Log(title = "质量体系文件历史-查看文件")
    @ApiOperation(value = "质量体系文件历史-查看文件")
    @GetMapping(value = "/getLsZltxwjFile")
    public void getLsZltxwjFile(@RequestParam(value = "id",defaultValue = "") String fileId,
                                @RequestParam(value = "symc",defaultValue = "") String symc,
                                @RequestParam(value = "fuserid",defaultValue = "") String fuserid,
                                HttpServletResponse response) {
        if (StringUtils.isEmpty(fileId)){
            log.error("质量体系文件id为空");
            throw new BusinessException("质量体系文件参数为空");
        }

        SpcyZltxwjHistory zltxwj = spcyZltxwjHistoryService.getById(fileId);
        if (zltxwj == null){
            throw new BusinessException("质量体系文件id为-{}的文件记录不存在"+fileId);
        }

        if (StringUtils.isNotBlank(fuserid)){
            String realname = ycSysUserMapper.findRealnameById(fuserid);
            symc = StringUtils.isNotBlank(realname) ? realname+DateConversionUtils.DateToString(new Date()) : symc;
        }

        // 文档才能转换
        if (!(zltxwj.getFwjlx().equals(".doc") || zltxwj.getFwjlx().equals(".docx"))){
            if (zltxwj.getFwjlx().equals(".pdf")) {
                txwjFlowService.historyZltxwjToTempPdf(zltxwj, zltxwj.getFwjlx(), true, symc, response);
            }else {
                localFileUploadUtils.ejzLocalFileURlByZltxwj(zltxwj.getFwjlj(), response);
            }
        }else {
            txwjFlowService.historyZltxwjToTempPdf(zltxwj, zltxwj.getFwjlx(), true, symc, response);
        }
    }

    @Log(title = "宣贯培训文件-查看文件/下载")
    @ApiOperation(value = "宣贯培训文件-查看文件/下载")
    @GetMapping(value = "viewXgpxwj")
    public void viewXgpxwj(@RequestParam(value = "id",defaultValue = "") @ApiParam("宣贯培训文件id") String fileId,
                           @RequestParam(value = "symc",defaultValue = "") @ApiParam("水印名称") String symc,
                           @RequestParam(value = "fuserid",defaultValue = "") @ApiParam("用户id非必填，主要用于水印") String fuserid,
                           HttpServletResponse response) throws IOException {
        if (StringUtils.isEmpty(fileId)){
            response.setContentType("text/html");
            response.setCharacterEncoding("UTF-8");
            PrintWriter writer = response.getWriter();
            writer.println("宣贯文件参数为空！");
            writer.close(); // 不要忘记关闭PrintWriter
            return;
        }

        SpcyZltxwjBasic zltxwj = spcyZltxwjXgpxwjMapper.selectTxwjBaseById(fileId);
        if (zltxwj == null){
            response.setContentType("text/html");
            response.setCharacterEncoding("UTF-8");
            PrintWriter writer = response.getWriter();
            writer.println("宣贯体系文件不存在！");
            writer.close(); // 不要忘记关闭PrintWriter
            return;
        }

        if (StringUtils.isNotBlank(fuserid)){
            String realname = ycSysUserMapper.findRealnameById(fuserid);
            symc = StringUtils.isNotBlank(realname) ? realname+DateConversionUtils.DateToString(new Date()) : symc;
        }

        if (StringUtils.isBlank(zltxwj.getFpdfurl())){
            if (StringUtils.isNotBlank(zltxwj.getFwjlj())){
                SpcyZltxwjBasic zltxwj2 = null;
                if (StringUtils.isBlank(zltxwj.getFzt()) || zltxwj.getFzt().equals(SpcyConstant.Zltxwj_Zt_Yx)){
                    zltxwj2 = txwjFlowService.zltxwjToPdf(zltxwj, false, true, false);
                }else {
                    zltxwj2 = txwjFlowService.zltxwjToPdf(zltxwj, false, true, true);
                }

                if (zltxwj2 != null && StringUtils.isNotBlank(zltxwj2.getFpdfurl())) {
//                    localFileUploadUtils.ejzLocalFileURlByZltxwj(zltxwj2.getFpdfurl(), response);

                    this.ejzFileSy(zltxwj2.getFpdfurl(), symc, response);

                }else {
                    localFileUploadUtils.ejzLocalFileURlByZltxwj(zltxwj.getFwjlj(), response);
                }
            }else {
                throw new BusinessException("质量体系文件id为-{}的文件不存在"+fileId);
            }
        }else {
//            localFileUploadUtils.ejzLocalFileURlByZltxwj(zltxwj.getFpdfurl(), response);
            this.ejzFileSy(zltxwj.getFpdfurl(), symc, response);
        }
    }

    /** 水印文件下载(pdf) */
    private void ejzFileSy(String fileNameUrl, String symc, HttpServletResponse response){
        if (StringUtils.isBlank(symc)){
            localFileUploadUtils.ejzLocalFileURlByZltxwj(fileNameUrl, response);
        }else {
            String wjhz = Util.getWjHz(fileNameUrl);

            if (localFileUploadUtils.isEnableMinioZltxwjFile()) {
                InputStream minioInput = spcyMinioUtils.getObject(fileNameUrl);
                if (minioInput == null) {
                    throw new BusinessException("文件流不存在！");
                }
                File file = localFileUploadUtils.asFile(minioInput, wjhz);

                localFileUploadUtils.ejzLocalFileSy(file.getAbsolutePath(), wjhz, symc, response);
            } else {
                String path = localFileUploadUtils.getZdyFileAbsUrl(fileNameUrl);
                localFileUploadUtils.ejzLocalFileSy(path, wjhz, symc, response);
            }
        }
    }

    /** 水印文件下载(pdf) */
    private void ejzFgbzkFileSy(String fileNameUrl, String symc, HttpServletResponse response){
        if (StringUtils.isBlank(symc)){
            localFileUploadUtils.ejzLocalFileURlByFgbzk(fileNameUrl, response);
        }else {
            String wjhz = Util.getWjHz(fileNameUrl);

            if (localFileUploadUtils.isEnableMinioFgbzkFile()) {
                InputStream minioInput = spcyMinioUtils.getObject(fileNameUrl);
                if (minioInput == null) {
                    throw new BusinessException("文件流不存在！");
                }
                File file = localFileUploadUtils.asFile(minioInput, wjhz);

                localFileUploadUtils.ejzLocalFileSy(file.getAbsolutePath(), wjhz, symc, response);
            } else {
                String path = localFileUploadUtils.getZdyFileAbsUrl(fileNameUrl);
                localFileUploadUtils.ejzLocalFileSy(path, wjhz, symc, response);
            }
        }
    }
}
